package com.knowledge.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.knowledge.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MetaHandler implements MetaObjectHandler {

    private static final String CREATE_TIME = "createTime";
    private static final String CREATE_BY = "createBy";
    private static final String UPDATE_TIME = "updateTime";
    private static final String UPDATE_BY = "updateBy";

    /**
     * 新增数据执行
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String userId= getUserId();
        if (metaObject.hasGetter(CREATE_BY) && metaObject.getValue(CREATE_BY) == null) {
            this.setFieldValByName(CREATE_BY, userId, metaObject);
        }
        if (metaObject.hasGetter(CREATE_TIME) && metaObject.getValue(CREATE_TIME) == null) {
            this.setFieldValByName(CREATE_TIME, new Date(), metaObject);
        }
    }

    /**
     * 更新数据执行
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String userId= getUserId();
        if (metaObject.hasGetter(UPDATE_TIME) ) {
            this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
        if (metaObject.hasGetter(UPDATE_BY)) {
            this.setFieldValByName(UPDATE_BY, userId, metaObject);
        }
    }

    private String getUserId(){
        String userId = null;
        try {
            userId = SecurityUtils.getUserId().toString() != null ? SecurityUtils.getUserId().toString() : null;
        } catch (Exception e) {
            return null;
        }
        return userId;
    }
}
